import requests

import os

from a import JsReader

headers = {
    "accept": "*/*",
    "accept-encoding": "gzip, deflate, br",
    "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
    "cache-control": "max-age=0",
    "content-length": "388",
    "content-type": "application/x-www-form-urlencoded",
    "origin": "https://music.163.com",
    "referer": "https://music.163.com/search/",
    "sec-ch-ua": '" Not A;Brand";v="99", "Chromium";v="99", "Microsoft Edge";v="99"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"Windows"',
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.55"
}
headers2 = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36 Edg/99.0.1150.55"
}
cookies = {'_ntes_nnid': 'c661c7af590aad7c2c5a3814a51fd074,1643556768166', '_ntes_nuid': 'c661c7af590aad7c2c5a3814a51fd074', '_iuqxldmzr_': '32', 'WEVNSM': '1.0.0', 'WNMCID': 'rnywax.1643771178136.01.0', 'NMTID': '00Oc6JDLcjQHLX6GEOyokKouuE97SQAAAF-uGW30g', 'WM_TID': 'byAIsaOLLQBEBBABUBZ6ucwoCRTaCIXN', 'ntes_kaola_ad': '1', 'timing_user_id': 'time_L6z8m8BaAL', '_ga': 'GA1.1.237845654.1647744153', '_ga_C6TGHFPQ1H': 'GS1.1.1647744153.1.0.1647744155.0', 'Qs_lvt_382223': '1647744156', 'Qs_pv_382223': '298370244042814400', 'WM_NI': '9%2BmPUzqMaZa1Zax%2FVyXt8HBxKfy6xr6ce%2BYVT33FCTk4Cq%2FLCo6ao%2FfIH1Gy1%2B%2FEUzgnaMRkCgke88yl6OZybVo5e4Q2IPTkYTOb5lQY4vAY8qruhLy0zUe0%2F40HAJ0hQ3U%3D', 'WM_NIKE': '9ca17ae2e6ffcda170e2e6ee8df43badb6ad9bc57ff28e8ba6c85f869a8aabaa3ef5baadd8c844fb95a3abcf2af0fea7c3b92afbf5a3b1d872b393afbbe43b9abfb8d0d5739cacf8a9c17489bab7d7fb7af6bdabccdc5e98edfda7c260a9ec8d92ae4881b1fa82ee25a69788d2c673f3f5e1a6d872a5b2afaed16181b9a586bb34bbb4fab0d973a28aa1d6e84093ee87b1d7619b8c8183b8689387fc97c453fcafbe96eb48bbf0b6b6e83cedec00a9c442f4b89fd4d837e2a3', 'JSESSIONID-WYYY': 'VRjp6Goniy4nAKhPGlnE86pJVGqmrxZH18jrC4dC4X5fJZEbjHznQdwKGrQfgrFGtaDWWq3MJQvCKbtysztznm%2Fnwig%2FVSC7bKyVHpEdcg1attb4rwFk1OUDcmJuHGRthl8D2SatckR%2FgUIlNT6T0e%2F0Ts9hgYZX0b%2BnJJQogfpcH%2Br1%3A1648707929449'}
cookies2 = {'MUSIC_A_T': '1452351475872', 'MUSIC_R_T': '1466603630805', '_ntes_nnid': 'c661c7af590aad7c2c5a3814a51fd074,1643556768166', '_ntes_nuid': 'c661c7af590aad7c2c5a3814a51fd074', '_iuqxldmzr_': '32', 'WEVNSM': '1.0.0', 'WNMCID': 'rnywax.1643771178136.01.0', 'NMTID': '00Oc6JDLcjQHLX6GEOyokKouuE97SQAAAF-uGW30g', 'WM_TID': 'byAIsaOLLQBEBBABUBZ6ucwoCRTaCIXN', 'ntes_kaola_ad': '1', 'timing_user_id': 'time_L6z8m8BaAL', '_ga': 'GA1.1.237845654.1647744153', '_ga_C6TGHFPQ1H': 'GS1.1.1647744153.1.0.1647744155.0', 'Qs_lvt_382223': '1647744156', 'Qs_pv_382223': '298370244042814400', 'WM_NI': '9%2BmPUzqMaZa1Zax%2FVyXt8HBxKfy6xr6ce%2BYVT33FCTk4Cq%2FLCo6ao%2FfIH1Gy1%2B%2FEUzgnaMRkCgke88yl6OZybVo5e4Q2IPTkYTOb5lQY4vAY8qruhLy0zUe0%2F40HAJ0hQ3U%3D', 'WM_NIKE': '9ca17ae2e6ffcda170e2e6ee8df43badb6ad9bc57ff28e8ba6c85f869a8aabaa3ef5baadd8c844fb95a3abcf2af0fea7c3b92afbf5a3b1d872b393afbbe43b9abfb8d0d5739cacf8a9c17489bab7d7fb7af6bdabccdc5e98edfda7c260a9ec8d92ae4881b1fa82ee25a69788d2c673f3f5e1a6d872a5b2afaed16181b9a586bb34bbb4fab0d973a28aa1d6e84093ee87b1d7619b8c8183b8689387fc97c453fcafbe96eb48bbf0b6b6e83cedec00a9c442f4b89fd4d837e2a3', 'JSESSIONID-WYYY': 'PbANHtYGbujj7FVSC%5CWKV1DDEEW%2FSg8blHozh18mceSW1UvQDPN4H40WshiB9arGTdguWxglbxfkhIeCXv9BJKd8rgXWV%5CkzqHoHoM%2Fkiwh%2B2PDiOqWIEpPQjpPc9qg27KsawIIheKl8lzX1Q6XSO3FVzox2yVwlkYvRqD8RG%2BOEskuu%3A1648712007007'}

'''
    https://music.163.com/weapi/song/lyric?csrf_token= 第四个包
    https://music.163.com/weapi/feedback/weblog?csrf_token= 第二个包(使用cookies2)
    https://music.163.com/weapi/cloudsearch/get/web?csrf_token= 第三个包(数据包)(使用cookies)

    '{"hlpretag":"<span class=\\"s-fc7\\">","hlposttag":"</span>","s":"%s","type":"1","offset":"0","total":"true","limit":"30","csrf_token":""}' #搜索指令
    '{"ids":"[%s]","level":"standard","encodeType":"aac","csrf_token":""}' #请求歌曲指令
'''

url1 = "https://music.163.com/weapi/cloudsearch/get/web?csrf_token=" # 搜索包请求地址
url2 = "https://music.163.com/weapi/song/enhance/player/url/v1?csrf_token=" # 歌曲包请求地址
j = JsReader()

def get_song_ls(singer):
    h = j.run('{"hlpretag":"<span class=\\"s-fc7\\">","hlposttag":"</span>","s":"%s","type":"1","offset":"0","total":"true","limit":"30","csrf_token":""}' % singer)
    form_data = dict(params=h['encText'], encSecKey=h['encSecKey'])
    r = requests.post(url1, data=form_data, headers=headers, cookies=cookies)
    r.encoding = 'utf-8'
    song_msg_ls = []
    for i in r.json()['result']['songs']:
        song_d = {}
        song_d['name'] = i['name']
        song_d['id'] = i['id']
        song_msg_ls.append(song_d)
    return song_msg_ls

def download_music(song_msg_ls:list, filepath:str):
    for i in song_msg_ls:
        k = i['name']
        v = i['id']
        h = j.run('{"ids":"[%s]","level":"standard","encodeType":"aac","csrf_token":""}' % v)
        form_data = dict(params=h['encText'], encSecKey=h['encSecKey'])
        r = requests.post(url2, data=form_data, headers=headers, cookies=cookies)
        r.encoding = 'utf-8'
        
        try:
            m_u = r.json()['data'][0]['url']
            r = requests.get(m_u, headers=headers2)
        except:
            print('lose:', r.text)
        else:
            with open(os.path.join(filepath, k + m_u[-4:]) , 'wb') as f:
                f.write(r.content)

if __name__ == "__main__":
    singer = "刘德华"           # 歌手名
    filepath = "d:/music"      # 音乐文件存储位置
    if not os.path.exists(filepath):
        os.makedirs(filepath)
    download_music(get_song_ls(singer), filepath)